package com.zhida.smartcontrol.pagectrl.projectdetail.zonemanager.adddevice;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jay.tools.utils.file_util.AssetUtils;
import com.yanzhenjie.kalle.Params;
import com.zhida.smartcontrol.common.Api;
import com.zhida.smartcontrol.common.Const;
import com.zhida.smartcontrol.knet.KalleCallBack;
import com.zhida.smartcontrol.mvp.BasePresenterImpl;
import com.zhida.smartcontrol.pagectrl.ProjectListBean;
import com.zhida.smartcontrol.pagectrl.projectdetail.GroupBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author: tanjianpei
 * date: 2019/10/21 021 10:30
 * description:
 */
public class AddDevicePresenter extends BasePresenterImpl<AddDeviceContract.View> implements AddDeviceContract.Presenter {
    private int type;
    private String address;
    private String equipmentCode;
    private String groupId;
    private String imei;
    private String lat;
    private String lng;
    private String manufacturer;
    private String name;
    private String num;
    private String switchType;
    private String id;
    private String mDevicePic;
    private String group_id;
    private String projectBaseId;

    @Override
    public void check(int type, String address, String equipmentCode, String groupId, String imei, String lat,
                      String lng, String manufacturer, String name, String num, String switchType, String filePath, String id,String group_id, String projectBaseId) {
        if (TextUtils.isEmpty(name)) {
            mView.showMsg("请输入设备名称");
            return;
        }
        if (TextUtils.isEmpty(imei)) {
            mView.showMsg("请输入设备IMEI码");
            return;
        }
        if (TextUtils.isEmpty(equipmentCode)) {
            mView.showMsg("请输入设备编码");
            return;
        }
        if (TextUtils.isEmpty(num)) {
            mView.showMsg("请输入卡号");
            return;
        }
        if (TextUtils.isEmpty(switchType)) {
            mView.showMsg("请选择类别");
            return;
        }
        if (TextUtils.isEmpty(manufacturer)) {
            mView.showMsg("请输入生产厂家");
            return;
        }
        if (TextUtils.isEmpty(lat) || TextUtils.isEmpty(lng)) {
            mView.showMsg("请选择经纬度");
            return;
        }

        this.type = type;
        this.address = address;
        this.equipmentCode = equipmentCode;
        this.groupId = groupId;
        this.imei = imei;
        this.lat = lat;
        this.lng = lng;
        this.manufacturer = manufacturer;
        this.name = name;
        this.num = num;
        this.switchType = switchType;
        this.id = id;
        this.group_id = group_id;
        this.projectBaseId = projectBaseId;

        if (TextUtils.isEmpty(filePath)) {
            submit();
        } else {
            upLoad(filePath);
        }
    }

    private void upLoad(String filePath) {
        mKalleCenter.upLoad(Api.UPLOAD_PIC, filePath, true, new KalleCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                mDevicePic = result;
                submit();
            }

            @Override
            public void onFailed(String msg) {
                mView.showMsg(msg);
            }
        });
    }

    private void submit() {
        if (this.type == Const.TYPE_ADD) {
            addDevice();
        } else {
            editDevice();
        }
    }

    private void addDevice() {
        Map<String, Object> params = new HashMap<>();
        params.put("address", this.address);
        params.put("iccid", this.equipmentCode);
        params.put("groupId", this.groupId);
        params.put("imei", this.imei);
        params.put("lat", this.lat);
        params.put("lng", this.lng);
        params.put("manufacturer", this.manufacturer);
        params.put("name", this.name);
        params.put("equipmentCode", this.num);
        params.put("switchType", this.switchType);
        params.put("devicePic", this.mDevicePic);
        mKalleCenter.postJson(Api.DEVICE_ADD, params, true, new KalleCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                mView.onSuccess("添加成功");
            }

            @Override
            public void onFailed(String msg) {
                mView.showMsg(msg);
            }
        });
    }

    private void editDevice() {
        Map<String, Object> params = new HashMap<>();
        params.put("id", this.id);
        params.put("address", this.address);
        params.put("equipmentCode", this.equipmentCode);
        params.put("lat", this.lat);
        params.put("lng", this.lng);
        params.put("manufacturer", this.manufacturer);
        params.put("name", this.name);
        params.put("num", this.num);
        params.put("devicePic", this.mDevicePic);
        if (group_id!=null&&!group_id.equals("")){
            params.put("groupsId", this.group_id);
        }
        if (projectBaseId!=null&&!projectBaseId.equals("")){
            params.put("projectBaseId", this.projectBaseId);
        }
        mKalleCenter.putJson(Api.DEVICE_EDIT, params, true, new KalleCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                mView.onSuccess("编辑成功");
            }

            @Override
            public void onFailed(String msg) {
                mView.showMsg(msg);
            }
        });
    }

    @Override
    public void initJsonData() {
        List<JsonBean> provinceList = new ArrayList<>();
        List<List<String>> pCityList = new ArrayList<>();
        List<List<List<String>>> areaList = new ArrayList<>();

        String JsonData = AssetUtils.loadAsset2Str(mView.getContext(), "province.json");
        List<JsonBean> jsonBean = parseData(JsonData);

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        provinceList = jsonBean;

        // 遍历省份
        for (int i = 0; i < jsonBean.size(); i++) {
            //该省的城市列表（第二级）
            List<String> cityList2 = new ArrayList<>();
            //该省的所有地区列表（第三极）
            List<List<String>> province_AreaList = new ArrayList<>();

            //遍历该省份的所有城市
            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                //添加城市
                cityList2.add(cityName);
                //该城市的所有地区列表
                List<String> city_AreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                JsonBean.CityBean cityBean = jsonBean.get(i).getCityList().get(c);
                if (cityBean.getArea() == null || cityBean.getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(cityBean.getArea());
                }
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            // 添加城市数据
            pCityList.add(cityList2);

            // 添加地区数据
            areaList.add(province_AreaList);
        }

        mView.showJsonData(provinceList, pCityList, areaList);
    }

    private List<JsonBean> parseData(String result) {//Gson 解析
        List<JsonBean> jsonBeans = new ArrayList<>();
        try {
            JSONArray array = JSON.parseArray(result);
            for (int i = 0; i < array.size(); i++) {
                JSONObject o = (JSONObject) array.get(i);
                String name = o.getString("name");
                List<JsonBean.CityBean> citys = o.getJSONArray("city").toJavaList(JsonBean.CityBean.class);

                JsonBean bean = new JsonBean();
                bean.setName(name);
                bean.setCityList(citys);
                jsonBeans.add(bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonBeans;
    }

}
